#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
商户进件修改示例
"""

import os
import sys
import uuid

# 添加项目根目录到Python路径，确保能够导入jlpay包
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from examples.base_example import BaseExample
from jlpay.services.openmerch.register.merchant_service import MerchantService
from jlpay.model.openmerch.register.merchant import MerchantIncomingModifyRequest

# =================== 常量定义 =====================
# 产品类型常量
PRODUCT_TYPE_QR_CODE = "01"  # 扫码商户：适用于码牌类商户，支持微信/支付宝/银联二维码交易
PRODUCT_TYPE_STANDARD = "02"  # 标准商户：适用于POS类商户，支持银行卡+微信/支付宝/银联二维码交易
PRODUCT_TYPE_SCENE = "03"  # 场景商户：特定准入商户标准,以人工申请结果为准
PRODUCT_TYPE_SAAS = "04"  # SaaS商户：适用于SaaS类商户，支持微信/支付宝/银联二维码/银行卡交易

# 签约模式常量
SIGN_MODE_PAPER = "P"  # 线下纸质协议
SIGN_MODE_ELECTRONIC = "E"  # 电子签章协议
SIGN_MODE_JLPAY = "J"  # 嘉联电子协议

# 联系人类型常量
CONTACT_TYPE_LEGAL_PERSON = "65"  # 经营者/法人
CONTACT_TYPE_OPERATOR = "66"  # 经办人（经商户授权办理支付业务的人员）

# 商户身份类型常量
MERCH_TYPE_MICRO = "0"  # 小微
MERCH_TYPE_ENTERPRISE = "1"  # 营业执照、政府机关、事业单位或其他组织

# 结算类型常量
SETTLE_TYPE_LEGAL_PERSON_CARD = "01"  # 打款至法人银行卡
SETTLE_TYPE_PUBLIC_ACCOUNT = "02"  # 打款至对公账户
SETTLE_TYPE_PRIVATE_AUTHORIZED = "03"  # 对私授权收款，打款至他人银行卡
SETTLE_TYPE_PUBLIC_AUTHORIZED = "04"  # 对公授权收款，打款至他人对公账户

# 结算关系常量
SETTLE_RELATION_SHAREHOLDERS = "01"  # 股东/雇佣
SETTLE_RELATION_BRANCHES = "02"  # 总分公司
SETTLE_RELATION_PARENT_SUBSIDIARY = "03"  # 母子公司
SETTLE_RELATION_OTHER = "09"  # 其它

# 全局变量,用于存储当前使用的apply_id
current_apply_id = ""


class IncomingModifyExample(BaseExample):
    """商户进件修改示例类"""
    
    def __init__(self):
        """初始化示例类"""
        super().__init__("examples.merchant_incoming")
        # 创建商户服务
        self.service = MerchantService(self.config)
    
    def demo(self):
        """执行商户进件修改示例"""
        self.logger.info("开始执行商户进件修改示例")
        
        # 创建商户进件修改请求
        request = MerchantIncomingModifyRequest()
        
        # 设置各项信息，复用大部分build_*函数
        request.set_base_info(self.build_base_info(is_modify=True))
        request.set_identification_info(self.build_identification_info())
        
        # 可以覆盖部分信息进行修改
        business_info = self.build_business_info()
        business_info["merch_shortname"] = "深圳市泰思便利店"  # 修改商户名称
        request.set_business_info(business_info)
        
        request.set_settlement_info(self.build_settlement_info())
        request.set_settlement_rule(self.build_settlement_rule())
        request.set_additional_info(self.build_additional_info())
        request.set_sms_config(self.build_sms_config())
        request.set_func_info(self.build_func_info())
        # request.set_chain_store_info(self.build_chain_store_info())
        # request.set_brand_info(self.build_brand_info())
        
        # 发送请求并处理响应
        response = self.send_request_and_handle_response(
            self.service.merchant_incoming_modify,
            "商户进件修改",
            request
        )
        
        # 处理响应结果
        if response and response.is_success():
            self.logger.info(f"进件修改成功！")
            self.logger.info(f"响应报文：{response.to_dict()}")
        else:
            self.logger.error("进件修改失败")
            if response:
                self.logger.error(f"响应报文：{response.to_dict()}")
        
        self.logger.info("进件修改示例执行完毕")
    
    def generate_apply_id(self):
        """生成唯一的apply_id"""
        global current_apply_id
        current_apply_id = f"1vzougr30f9vcw{uuid.uuid4().hex[:16]}"
        return current_apply_id
    
    def build_base_info(self, is_modify=False):
        """构建商户基础信息"""
        apply_id = "1vzougr30f9vcwae3d7ef28e0c42df"
        
        base_info = {
            "apply_id": apply_id,
            "product_type": PRODUCT_TYPE_SAAS,
            "sign_mode": SIGN_MODE_ELECTRONIC,
            "delegatee_sign_mode": SIGN_MODE_ELECTRONIC,
            "agreement_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
            "agent_id": "50720711",
            "qrcode_term_auto": "1",
            "contact_info": {
                "contact_type": CONTACT_TYPE_LEGAL_PERSON,
                # 以下敏感字段在实际使用中需要填写
                # "contact_name": "王一",
                # "contact_phone": "13800138000",
                # "contact_id_no": "替换为身份证号"
            }
        }
        return base_info
    
    def build_identification_info(self):
        """构建商户身份信息"""
        identification_info = {
            "merch_type": MERCH_TYPE_ENTERPRISE,
            "license_info": {
                "license_type": "02",  # 企业
                "license_name": "营业执照上的名称",
                "license_no": "91330108MABTT5NP6U",
                "period_begin": "2024-01-01",
                "period_end": "2030-01-01",
                "license_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
                "business_scope": "经营范围"
            },
            "identity_info": {
                "id_doc_type": "01",  # 身份证
                "id_card_name": "王一",
                "id_card_no": "110101199003077758",
                "legal_person_phone": "13800138000",
                "card_period_begin": "2024-01-01",
                "card_period_end": "2030-01-01",
                "id_card_address": "住址",
                "id_card_copy": "jlpay-test/managefile/2024/02/28/1709081474283_7ddfb60f42d94f8094ec88d7c78ec4a3.png",
                "id_card_national": "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
            }
        }
        return identification_info
    
    def build_business_info(self):
        """构建商户经营信息"""
        business_info = {
            "merch_shortname": "商户经营名称",
            "mcc_code": "5311",
            "address_code": "440305",
            "address_detail": "深圳市南山区工业一路22501号",
            "door_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
            "indoor_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
            "cashier_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
        }
        return business_info
    
    def build_settlement_info(self):
        """构建商户结算账户信息"""
        settlement_info = {
            "settle_type": SETTLE_TYPE_LEGAL_PERSON_CARD,
            "settle_relation": SETTLE_RELATION_BRANCHES,
            "account_info": {
                "account_no": "6227001215950896532",
                "account_name": "王一",
                "cert_type": "01",  # 身份证
                "bank_code": "082",
                "bank_branch_id": "105584000370",
                "bank_branch_name": "中国建设银行股份有限公司深圳罗湖支行",
                "account_pic": "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg",
            },
            "other_info": {
                "identity_face_pic": "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg"
            }
        }
        return settlement_info
    
    def build_rate_info(self, fee_calc_type, rate, min_amt="0", max_amt="-1", fixed="0", bottom="0", top="-1", step="0", base_amount="0", base_fee="0"):
        """
        构建费率信息条目
        
        Args:
            fee_calc_type: 费用计算类型代码
            rate: 费率百分比
            min_amt: 最小金额
            max_amt: 最大金额，"-1"表示不限
            fixed: 固定费用
            bottom: 保底费用
            top: 封顶费用，"-1"表示不封顶
            step: 阶梯
            base_amount: 基础金额
            base_fee: 基础费用
        
        Returns:
            费率信息字典
        """
        return {
            "fee_calc_type": fee_calc_type,
            "rate": rate,
            "min_amt": min_amt,
            "max_amt": max_amt,
            "fixed": fixed,
            "bottom": bottom,
            "top": top,
            "step": step,
            "base_amount": base_amount,
            "base_fee": base_fee
        }
    
    def build_settlement_rule(self):
        """构建商户结算规则和费率规则"""
        # 费率信息列表
        rate_info = [
            # 微信支付宝相关费率
            self.build_rate_info("30", "0.38"),  # 微信
            self.build_rate_info("31", "0.38"),  # 支付宝
            self.build_rate_info("03", "0.38", max_amt="100000"),  # 银联二维码
            
            # 银联内卡费率
            self.build_rate_info("01", "0.45", top="1900"),  # 银联内卡借记卡 (封顶19元)
            self.build_rate_info("02", "0.55"),  # 银联内卡贷记卡 (不封顶)
            
            # 银联外卡费率
            self.build_rate_info("11", "0.45", top="1900"),  # 银联外卡借记卡
            self.build_rate_info("12", "0.55"),  # 银联外卡贷记卡
            
            # 外币支付相关费率
            self.build_rate_info("20", "0.60"),  # 外币DCC
            self.build_rate_info("21", "0.60"),  # 外币EDC
            self.build_rate_info("22", "0.60"),  # 外币EDC-VM
            self.build_rate_info("23", "0.55"),  # 外币EDC优惠-VM
            
            # 支付宝优享相关费率
            self.build_rate_info("34", "0.38", top="1900"),  # 支付宝优享借记卡
            self.build_rate_info("35", "0.40"),  # 支付宝优享贷记卡
            
            # 万事网联相关费率
            self.build_rate_info("60", "0.38", top="1900"),  # 万事网联非接优惠
            self.build_rate_info("61", "0.45", top="1900"),  # 万事网联借记卡
            self.build_rate_info("62", "0.55"),  # 万事网联贷记卡
            
            # 快速提现费率
            self.build_rate_info("T0", "0.10", bottom="100"),  # 快速提现 (保底1元)
        ]
        
        settlement_rule = {
            "settle_info": {
                "settle_mode": "7",  # 仅D1，资金在交易完成第二个自然日结算
                "day_cut": "000000",  # 账单日切点为昨天0点到今天0点
                "settle_session": "040000",  # 4点付款
                "account_change_flag": "0",  # 不允许商户后台变更结算账户
            },
            "rate_info": rate_info
        }
        return settlement_rule
    
    def build_additional_info(self):
        """构建其他附加信息"""
        additional_info = {
            "report_info": {
                # 可按需添加以下字段
                # "wechat_jsapi_path": "https://xxx.com/pay/",
                # "wechat_sub_appid": "wx1234567890",
                # "wechat_pid": "12345678",
                # "alipay_pid": "12345678",
            }
        }
        return additional_info
    
    def build_sms_config(self):
        """构建短信配置"""
        sms_config = {
            # 可按需添加以下字段
            # "merch_login_notify": "1",
            # "withdraw_password_notify": "1",
            # "sign_notify": "1",
            # "realname_notify": "1"
        }
        return sms_config
    
    def build_func_info(self):
        """构建商户业务功能配置"""
        func_info = {
            # 可按需添加以下字段
            # "open_functions": ["01", "02"]
        }
        return func_info
    
    def build_chain_store_info(self):
        """构建品牌连锁商户进件配置信息"""
        chain_store_info = {
            # 可按需添加以下字段
            # "level": "1",
            # "main_merch_no": "12345678",
            # "at_mode": "0"
        }
        return chain_store_info
    
    def build_brand_info(self):
        """构建品牌信息"""
        brand_info = {
            # 可按需添加以下字段
            # "brand_name": "XX品牌",
            # "brand_mark_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
            # "brand_auth_pic": "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
            # "contact_name": "王一",
            # "contact_phone": "13800138000"
        }
        return brand_info


if __name__ == "__main__":
    logger = IncomingModifyExample().logger
    logger.info("=" * 50)
    logger.info("===== 商户进件修改示例 开始 =====")
    logger.info("=" * 50)
    
    example = IncomingModifyExample()
    example.demo()
    
    logger.info("\n" + "=" * 50)
    logger.info("===== 商户进件修改示例执行完毕 =====")
    logger.info("=" * 50) 